<template>
  <div class="create-post-page">
    <h4>{{ isEditMode ? '编辑文章' : '新建文章' }}</h4>
    <UploaderFile
        action="/upload"
        class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
        style="height:300px" :before-upload="uploadedCheck" @file-uploaded="handleFileUploaded" :uploaded="uploadedData"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <!--            <span class="scr-only"></span>-->
          </div>
        </div>
        <h2>正在上传</h2>
      </template>
      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url" alt="">
          <h3>点击重新上传</h3>
        </div>

      </template>
      <!-- <template #loading>
    <div class="d-flex">
    <div class="spinner-border text-secondary" role="status">
     <span class="sr-only"></span>
     </div>
     <h2>正在上传</h2>
     </div>
    </template>
    <template #uploaded="dataProps">
     </template> -->

    </UploaderFile>
    <!--    <input type="file" name="file" @change.prevent="handleFileChange">-->
    <vaildate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <vaildate-input placeholder="请输入文章标题" type="text" :rules="titleRules" v-model="titleVal"
                        @value="titleValue"></vaildate-input>
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <textarea ref="textArea"></textarea>
        <vaildate-input placeholder="请输入文章详情" rows="10" tag="textarea" :rules="contentRules" v-model="contentVal"
                        @value="contentValue" type="text"></vaildate-input>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{ isEditMode ? '更新文章' : '发表文章' }}</button>
      </template>
    </vaildate-form>

  </div>
</template>

<script lang="ts">
import {defineComponent, onMounted, ref} from "vue";
import {useStore} from "vuex";
import {GolbalDataProps, ResponseType, ImageProps, PostProps, UserProps} from "@/store";
import {useRoute} from "vue-router";
import {useRouter} from "vue-router";
import vaildateForm from "@/components/VaildateForm.vue";
import vaildateInput, {RulesProp} from "@/components/VaildateInput.vue";
// import {PostProps} from "@/testData";
import axios from "axios";
import UploaderFile from "@/components/UploaderFile.vue";
import {beforUploadCheck} from "@/hooks/helper";
import createMessage from "@/hooks/createMessage";
import EasyMDE from "easymde";

export default defineComponent({
  name: 'CreatePost',
  components: {
    vaildateForm,
    vaildateInput,
    UploaderFile
  },

  setup() {
    const textArea = ref<null | HTMLTextAreaElement>(null)
    const titleVal = ref('')
    const titleValue = (val: string) => {
      titleVal.value = val
    }
    const router = useRouter()
    const route = useRoute()
    const isEditMode = !!route.query.id
    const uploadedData = ref()
    const store = useStore<GolbalDataProps>()
    const titleRules: RulesProp = [
      {type: 'required', message: '文章标题不能为空'}
    ]
    const contentVal = ref('')
    const contentValue = (val: string) => {
      contentVal.value = val
    }
    const contentRules: RulesProp = [
      {type: 'required', message: '文章详情不能为空'}
    ]
    const uploadedCheck = (file: File) => {
      const result = beforUploadCheck(file, {format: ['image/jpeg', 'image/png'], size: 1})
      const {passed, error} = result
      if (error === 'format') {
        createMessage('上传图片只能是JGP/PNG格式', 'error')
      }
      if (error === 'size') {
        createMessage('上传图片不能超过1KB', 'error')
      }
      return passed
    }
    let imageId = ''
    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
    }
    onMounted(() => {
      if(textArea.value){
        const easyMDEInstance = new EasyMDE({ element:textArea.value})
      }
      if (isEditMode) {
        store.dispatch('fetchPost', route.query.id).then((rwaData: ResponseType<PostProps>) => {
          const currentPost = rwaData.data
          if (currentPost.image) {
            uploadedData.value = {data: currentPost.image}
          }
          titleVal.value = currentPost.title
          contentVal.value = currentPost.content || ''
        })
      }
    })
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const {column, _id} = store.state.user
        if (column) {
          const newPost: PostProps = {
            // id: new Date().getTime(),
            // _id: '',
            title: titleVal.value,
            content: contentVal.value,
            column,
            // createdAt: new Date().toLocaleString(),
            author: _id,
            // _id: "",
            // createdAt: ""
          }
          if (imageId) {
            newPost.image = imageId
          }
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode ? {
            id: route.query.id,
            payload: newPost
          } : {
            newPost
          }
          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表成功，2秒后跳转到文章', 'success')
            setTimeout(() => {
              router.push({name: 'column', params: {id: column}})
            }, 2000)
          })
          //自动跳转详情页
          // store.commit('createPost', newPost)
          // router.push({name: 'column', params: {id: columnId}})
        }
      }
    }
    // const handleFileChange = (e: Event) => {
    //   const target = e.target as HTMLInputElement
    //   const files = target.files
    //   if (files) {
    //     const uploadedFile = files[0]
    //     const formData = new FormData()
    //     formData.append(uploadedFile.name, uploadedFile)
    //     axios.post('/upload', formData, {
    //       headers: {
    //         'Content-Type': 'multipart/form-data'
    //       }
    //     }).then(resp => {
    //       console.log(resp)
    //     })
    //   }
    // }


    return {
      titleVal,
      titleRules,
      contentVal,
      contentRules,
      onFormSubmit,
      titleValue,
      contentValue,
      // handleFileChange,
      uploadedCheck,
      handleFileUploaded,
      isEditMode,
      uploadedData,
      textArea
    }
  }
})
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}

.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
